const fs = require ('fs');
const path = require ('path');

const chartStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let chartIndex = 0;
const routeRefPath = './src/stores/index.js';
const storeArray = [];

const isFolder = obj => {
  if (obj.children) {
    return true;
  }
  return false;
};

const renderConfig = list => {
  let firstStage = [];

  createApi(list);

  list.forEach ((vl, i) => {
    const bool = isFolder (vl);
    if (bool) {
      createFolder (vl);
      createStore ([vl]);
      createRouter ([vl]);
    } else {
      firstStage.push (vl.path);
      createFile ([vl]);
      createStore ([vl]);
      createRouter ([vl]);
    }
  });

  if (firstStage.length > 0) {
    const importStr = firstStage
      .map (vl => {
        vl = vl + 'Store';
        const storeName = vl.replace ('.js', '');
        return `import ${storeName} from "./${vl}";`;
      })
      .join ('');
      if(firstStage[0].indexOf('Store')<0) {
        firstStage = firstStage.map((vl)=> {
            vl += 'Store';
            return vl;
        })
      }

    const str = `
         ${importStr}
         export default {
             ${firstStage}
         }
        `;
    fs.writeFileSync ('./src/stores/module/index.js', str);
  }

  refRouter ();
  refStore ();
};

const createApi = (list) => {

    list.forEach((vl,i)=>{
        if(!!!vl.children) {
            const fileUrl = `./src/service/api/${vl.path}Api.js`;
            const bool = fs.existsSync(fileUrl);
            if(!bool) {
                fs.copyFileSync( './template/api/Api.js' ,fileUrl);
            }
        } else if(vl.children) {
            createApi(vl.children);
        }
    })
}

const createFolder = item => {
  const {path, fullPath} = item;
  const isExist = fs.existsSync (`./src/containers${fullPath}`);
  if (!isExist) {
    //创建jsx入口文件
    fs.mkdirSync (`./src/containers/${fullPath}`);
  }
  createFile (item.children);
};

const createFile = list => {
  list.forEach ((vl, i) => {
    if (!!!vl.children) {
      //文件信息
      //判断文件是否存在
      const fileUrl = `./src/containers${vl.fullPath}.js`;
      const bool = fs.existsSync (fileUrl);
      if (!bool) {
        fs.copyFileSync ('./template/containers/defaultContainer.js', fileUrl);
      }
      let data = fs.readFileSync (fileUrl, 'utf8');
      if (vl.template == 0) {
        data = data.replace ("const str = '';", `const str = '${vl.name}';`);
        data = data.replace ('tmplStore', `${vl.path}Store`);
        fs.writeFileSync (fileUrl, data);
      }
    } else {
      createFolder (vl);
    }
  });
};

const createStore = item => {
  item.forEach ((vl, i) => {
    if (vl.children) {
      const fileUrl = `./src/stores/module${vl.fullPath}`;
      const bool = fs.existsSync (fileUrl);
      if (!bool) {
        fs.mkdirSync (fileUrl);
        fs.copyFileSync ('./template/store/folder.js', fileUrl + '/index.js');
      }
      createStore (vl.children);
      let fileNames = fs.readdirSync (fileUrl);
      fileNames = fileNames
        .filter ((vl, i) => {
          return vl != 'index.js' && vl.indexOf ('.js') > 0;
        })
        .map (vl => {
          return vl.replace ('.js', '');
        });
      const importStr = fileNames
        .map (vl => {
          const storeName = vl.replace ('.js', '');
          return `import ${storeName} from "./${vl}";`;
        })
        .join ('');
      const str = `
            ${importStr}

            export default {
                ${fileNames}
            }
           `;
      fs.writeFileSync (fileUrl + '/index.js', str);
    } else {
      const fileUrl = `./src/stores/module${vl.fullPath}Store.js`;
      const bool = fs.existsSync (fileUrl);
      if (!bool) {
        fs.copyFileSync ('./template/store/InfoListTmpl.js', fileUrl);
        let data = fs.readFileSync (fileUrl, 'utf8');
        data = data.replace (/Tmpl/g, vl.path);
        fs.writeFileSync (fileUrl, data);
      }
    }
  });
};

const deepRoute = list => {
  return list.map ((vl, i) => {
    const obl = {};
    let str;
    if (vl.children) {
      const children = deepRoute (vl.children).toString ();
      str = `
            {
                label: "${vl.name}",
                path: "${vl.fullPath}",
                exact: true,
                children: [${children}]
            }
        `;
    } else {
      str = `
            {
                label: "${vl.name}",
                path: "${vl.fullPath}",
                exact: true,
                render: ${vl.path}Component
            }
        `;
    }
    return str;
  });
};

const deepRouteRef = (list, fn) => {
  return list.map ((vl, i) => {
    fn (vl);
    if (vl.children) {
      deepRouteRef (vl.children, fn);
    }
    return vl;
  });
};

const createRouter = list => {
  const routerTemplate = deepRoute (list);
  list.forEach ((vl, i) => {
    const fileUrl = `./src/router/routes/${vl.path}.js`;
    const bool = fs.existsSync (fileUrl);
    fs.writeFileSync (fileUrl, '');
    const componentNames = [];
    deepRouteRef ([vl], child => {
      if (child.children === undefined) {
        componentNames.push (child.path);
        fs.appendFileSync (
          fileUrl,
          `import ${child.path}Component from "@/containers${child.fullPath}";\n`
        );
        
        chartIndex++;
      }
    });
    fs.appendFileSync (
      fileUrl,
      `\nexport default ${routerTemplate[i].toString ()}`
    );
  });
};



const refRouter = () => {
  const routeIndex = './src/router/index.js';
  let routes = fs.readdirSync ('./src/router/routes');
  fs.writeFileSync (routeIndex, '');
  routes = routes.map ((vl, i) => {
    const str = vl.replace ('.js', '');
    fs.appendFileSync (routeIndex, `import ${str} from "./routes/${vl}";\n`);
    return str;
  });
  fs.appendFileSync (routeIndex, `\n`);
  fs.appendFileSync (routeIndex, `export default { ${routes.toString ()} }`);
};



const refStore = () => {
  fs.writeFileSync (routeRefPath, '');
  const fileAll = deepFile ('./src/stores/module');

  fs.appendFileSync (routeRefPath, `\n`);
  fs.appendFileSync (routeRefPath, `export default { ${storeArray.toString()} }`);
};

const deepFile = filePath => {
  //根据文件路径读取文件，返回文件列表
  var files =  fs.readdirSync (filePath);
      //遍历读取到的文件列表
      files.forEach (function (filename) {
        //获取当前文件的绝对路径
        var filedir = path.join (filePath, filename);
        //根据文件路径获取文件信息，返回一个fs.Stats对象
        const stats = fs.statSync (filedir);
            var isFile = stats.isFile (); //是文件
            var isDir = stats.isDirectory (); //是文件夹
            if (isFile) {
              if (filedir.indexOf ('index.js') >= 0) {
                filedir = filedir.replace ('src', '@');
                storeArray.push(`...Module${chartStr[chartIndex]}`);
                fs.appendFileSync (
                  routeRefPath,
                  `import Module${chartStr[chartIndex]} from "${filedir}";\n`
                );
                chartIndex++;
              }
            }
            if (isDir) {
              deepFile (filedir); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
            }
      });
};

const list = [{"id":56,"name":"人脸识别","path":"FaceRecognition","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":57,"name":"人体识别&追踪","path":"HumanRecognitionTracking","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":58,"name":"机动车识别","path":"MotorVehicleRecognition","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":59,"name":"机动车车牌识别","path":"VehicleLicensePlateRecognition","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":60,"name":"非机动车识别","path":"NonMotorVehicleRecognition","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":61,"name":" 人体追踪","path":"CrossBorderHeadTracking","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":62,"name":"行业OCR识别算法","path":"IndustryOCRRecognitionAlgorithms","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"},{"id":63,"name":"地址抽取","path":"AddressExtraction","pid":null,"template":0,"children":[],"isParent":false,"isGenerate":false,"username":"数据共享平台"}];

list.forEach((vl,i)=> {
  if(vl.isParent === false ) {
    vl.children = undefined;
  }
  vl.children && vl.children.forEach((child,key)=> {
    if(child.isParent === false ) {
      child.children = undefined;
    }
  })
})

const deep = (routerList, upperLevel = '') => {
  routerList.forEach ((vl, i) => {
    vl.fullPath = `${upperLevel}/${vl.path}`;
    if (vl.children) {
      deep (vl.children, vl.fullPath);
    }
  });
};

deep (list);
renderConfig (list);

//console.info(str.toString(),"打印信息");
